package a66weding.com.jiehuntong.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.HttpManager;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.UUID;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.home.BaseHomeActivity;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MusicBean;
import a66weding.com.jiehuntong.beans.SimpleBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.UpMusicBean;
import a66weding.com.jiehuntong.common.CommonAdapter;
import a66weding.com.jiehuntong.common.MyViewHolder;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.FileUtil;
import a66weding.com.jiehuntong.common.utils.LogUtil;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.common.utils.Utils;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;

/*主题音乐设置界面
 */
public class ThemeMusicActivity extends BaseHomeActivity implements View.OnClickListener, OnNetResultListener, AdapterView.OnItemClickListener {
    private Dialog dialog;
    private ListView lvMusic;
    private List<MusicBean.DataBean> mMusics;
    private CommonAdapter<MusicBean.DataBean> musicCommonAdapter;
    private MediaPlayer mediaPlayer;
    private int currentMusic;//选择默认的音乐指针该指针来着音乐列表的id
    private String currentMusicName;//当前音乐名字
    private int oldID;
    private int uId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_theme_music);
        currentMusicName = getIntent().getStringExtra("currentMusicName");
        currentMusic = getIntent().getIntExtra("musicIndex", 0);
        oldID = currentMusic;//记录旧id
        initView();
        uId = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
        getNetMusics();
    }

    public void getNetMusics() {
        //请求网络音乐列表
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, RequestCode.SURL + RequestCode.ALLMUSICLIST + uId, this, MusicBean.class, RequestCode.ALLMUSICLIST);
        HttpHandleUtil.executeCommonGet(this, httpRequestBean);
    }

    //初始化控件
    private void initView() {
        //自定义音乐几个字与点击事件
        TextView tv_custom_music = (TextView) findViewById(R.id.tv_custom_music);
        tv_custom_music.setOnClickListener(this);
        //显示后台提供的音乐列表
        lvMusic = (ListView) findViewById(R.id.lv_music);
        lvMusic.setOnItemClickListener(this);
        //头部导航
        TextView tv_tools_dayplan_backcontent = (TextView) findViewById(R.id.tv_tools_dayplan_backcontent);
        LinearLayout llay_toolsheader_back = (LinearLayout) findViewById(R.id.llay_toolsheader_back);
        TextView tv_tools_dayplan_title = (TextView) findViewById(R.id.tv_tools_dayplan_title);
        TextView tv_tools_dayplan_addtype1 = (TextView) findViewById(R.id.tv_tools_dayplan_addtype1);
        ImageView img_tools_dayplan_backcontent = (ImageView) findViewById(R.id.img_tools_dayplan_backcontent);
        img_tools_dayplan_backcontent.setOnClickListener(this);
        tv_tools_dayplan_backcontent.setText("   ");
        tv_tools_dayplan_title.setText("主题音乐");
        tv_tools_dayplan_addtype1.setText("保存");
        tv_tools_dayplan_addtype1.setVisibility(View.VISIBLE);
        tv_tools_dayplan_backcontent.setOnClickListener(this);
        llay_toolsheader_back.setOnClickListener(this);
        tv_tools_dayplan_backcontent.setOnClickListener(this);
        tv_tools_dayplan_addtype1.setOnClickListener(this);
    }

    //播放音乐
    private void playMusic(String url) {
        try {
            if (mediaPlayer == null) {
                mediaPlayer = new MediaPlayer();
            }
            mediaPlayer.stop();
            mediaPlayer.reset();
            //设置数据源
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepareAsync();
            //异步准备完成
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    mediaPlayer.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            stopMusic();
        }
    }

    // 停止音乐
    public void stopMusic() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    //点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llay_toolsheader_back:
                finish();
                break;
            case R.id.img_tools_dayplan_backcontent:
                finish();
                break;
            case R.id.tv_tools_dayplan_backcontent:
                finish();
                break;
            case R.id.tv_custom_music:
                upLoadMusic();
                break;
            case R.id.tv_tools_dayplan_addtype1:
                stopMusic();
                requsetNetSet();
                break;
        }
    }

    //请求网络设置当前的使用音乐
    private void requsetNetSet() {
        if (mMusics != null && lvMusic.getChildCount() > 0) {
            HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, RequestCode.SURL + RequestCode.THEMEMUSIC + "&uid=" + uId + "&mid=" + currentMusic, this, SimpleBean.class, RequestCode.THEMEMUSIC);
            HttpHandleUtil.executeCommonGet(this, httpRequestBean);
        } else {
            CUtils.showToast("未获取到主题音乐列表,无法设置主题音乐");
        }
    }
    public int READ=6;
    public void gotoMusic() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE}, READ);
        } else {
            Intent i = new Intent(ThemeMusicActivity.this, LocalMusicActivity.class);
            startActivityForResult(i, 999);
            stopMusic();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == READ) {
            if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    gotoMusic();
            } else {
                CUtils.showToast("请打开手机拍照权限后在操作");
            }
        }
    }
    /**
     * 上传音乐文件的弹窗
     */
    public void upLoadMusic() {
        View view = this.getLayoutInflater().inflate(R.layout.activity_tools_dialog_photo, null);
        Button photoBtn = (Button) view.findViewById(R.id.dialog_photo_button);
        Button cameraBtn = (Button) view.findViewById(R.id.dialog_camera_button);
        Button quxiaoBtn = (Button) view.findViewById(R.id.dialog_quxiao_button);
        cameraBtn.setText("自定义");
        cameraBtn.setTextSize(getResources().getDimension(R.dimen.font_size15));
        cameraBtn.setTextColor(getResources().getColor(R.color.colorFontGray2));
        photoBtn.setText("本地上传");
        photoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoMusic();
                dialog.dismiss();
            }
        });

        quxiaoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });


        dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = this.getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    //页面跳转后回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 999) {
            if (data != null) {
                final String musicPath = data.getStringExtra("musicPath");
                if (!musicPath.endsWith(".mp3")) {
                    CUtils.showToast("仅支持MP3格式");
                } else {
                    Tools.showSimpleDialog(ThemeMusicActivity.this, "是否上传选择的音频", "取消", "确定", new Tools.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            File file = new File(musicPath);
                            uploadfile(file);
                        }

                        @Override
                        public void doCancel() {
                        }
                    });
                }
            }
            if (requestCode == 69) {
                if (data != null) {//判断这个目的是为了防止用户未选择音乐或者文件返回的时候崩掉
                    final Uri uri = data.getData();
                    if (uri != null) {
                        String path = uri.getPath();
                        LogUtil.d("6969", path);
                        if (!path.endsWith(".mp3")) {
                            CUtils.showToast("仅支持MP3格式");
                        } else {
                            Tools.showSimpleDialog(ThemeMusicActivity.this, "是否上传选择的音频", "取消", "确定", new Tools.ClickListenerInterface() {
                                @Override
                                public void doConfirm() {
                                    File file = new File(uri.getPath());
                                    uploadfile(file);
                  /*              String path = file.getPath();
                                 String musicName = path.substring(path.lastIndexOf("/") + 1, path.length()).replaceAll("\\s", "");
                                Log.i("111", "音乐名: "+musicName+"音乐路径"+file.getPath());
                                //音乐
                                 String url = RequestCode.SURL + RequestCode.UPLOADMUSIC + uId + "&musicName=" + Utils.URLEncode(musicName);
                                //xUpLoading(url,file);
                                uploadfiles(file);*/
                                }

                                @Override
                                public void doCancel() {

                                }
                            });
                        }
                    }
                }
            }
        }
    }

    /**
     * 上传音乐
     * WeddingMobileApi/UpMusicUid?Token={Token}&uid={uid}&musicName={musicName}
     */
    private void uploadfile(final File saveFile) {
        String path = saveFile.getPath();
        LogUtil.d("666", path);
        final String musicName = path.substring(path.lastIndexOf("/") + 1, path.length()).replaceAll("\\s", "");
        LogUtil.d("666", musicName);
        // 弹框
        Tools.showWaitDialog(this, "上传中...", false);
        //音乐
        final String url = RequestCode.SURL + RequestCode.UPLOADMUSIC + uId + "&musicName=" + Utils.URLEncode(musicName);
        LogUtil.d("666", url);
        new Thread() {
            @Override
            public void run() {
                String result = uploadFile(saveFile, url);
                if (!TextUtils.isEmpty(result)) {
                    Gson gson = new Gson();
                    final UpMusicBean newMusic = gson.fromJson(result, new TypeToken<UpMusicBean>() {
                    }.getType());
                    if (newMusic != null && newMusic.getResCode().equals("0000")) {
                        if (newMusic != null && newMusic.getResCode().equals("0000")) {
                            currentMusic = newMusic.getData().getI_Id();
                            currentMusicName = newMusic.getData().getNvc_Name();
                            playMusic(newMusic.getData().getNvc_Path());
                            getNetMusics();
                        }
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                CUtils.showToast(newMusic.getMsg());
                            }
                        });
                    }
                    // 取消弹框
                    Tools.dismissWaitDialog();
                }
            }
        }.start();
    }

    /**
     * 具体上传音乐文件的实现
     */
    public String uploadFile(File file, String RequestURL) {
        String result = "";
        String BOUNDARY = UUID.randomUUID().toString();
        //边界标识 随机生成
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; //内容类型
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10 * 100000);
            conn.setConnectTimeout(10 * 100000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST"); //请求方式
            conn.setRequestProperty("Charset", "utf-8");
            //设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            if (file != null) {
                /**  当文件不为空，把文件包装并且上传 */
                OutputStream outputSteam = conn.getOutputStream();
                DataOutputStream dos = new DataOutputStream(outputSteam);
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + file.getName() + "\"" + LINE_END);
                sb.append("Content-Type: application/octet-stream; charset=utf-8" + LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024 * 100];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }

                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功
                 * 当响应成功，获取响应的流
                 */
                int res = conn.getResponseCode();
                LogUtil.d("6969", "响应吗" + res);
                if (res == 200) {
                    // 读取返回数据
                    StringBuffer strBuf = new StringBuffer();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        strBuf.append(line).append("\n");
                    }
                    result = strBuf.toString();
                    LogUtil.d("4545", "读取完成" + result);
                    reader.close();
                    return result;
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    //网络请求数据成功
    @Override
    public void onSucess(SuccessBean sucessbean) {
        if (sucessbean != null) {
            final Object data = sucessbean.getData();
            if (data instanceof MusicBean) {
                MusicBean mb = (MusicBean) data;
                if (mb != null && mb.getResCode() != null) {
                    if (mb.getResCode().equals("0000")) {
                        setData2List(mb);
                    } else {
                        CUtils.showToast(mb.getMsg());
                    }
                }
            } else if (data instanceof SimpleBean) {
                SimpleBean spb = (SimpleBean) data;
                if (spb != null && spb.getResCode() != null) {
                    if (spb.getResCode().equals("0000")) {
                       //保存完成后销毁页面并携带数据返回
                        Intent intent = new Intent();
                        if (mMusics != null && lvMusic.getChildCount() > 0) {
                            intent.putExtra("musicname", currentMusicName);
                            intent.putExtra("musicid", currentMusic);
                        }
                        setResult(99, intent);
                        finish();
                        //请柬内容有修改后调用该行代码
                        sendBroadcast(new Intent(ElectronicInvitationActivity.ACTION_REFRESH_INVITATION));
                        CUtils.showToast("设置主题音乐" + spb.getMsg());
                    } else {
                        CUtils.showToast("设置主题音乐" + spb.getMsg());
                    }
                }
            }
        }
    }

    private void setData2List(MusicBean mb) {
        mMusics = mb.getData();
        musicCommonAdapter = new CommonAdapter<MusicBean.DataBean>(this, mMusics, R.layout.item_music) {
            @Override
            public void convert(MyViewHolder holder, int position) {
                MusicBean.DataBean dataBean = mMusics.get(position);
                TextView tv_music = (TextView) holder.getView(R.id.tv_music);
                tv_music.setCompoundDrawables(null, null, null, null);//全部默认不设置
                tv_music.setText(dataBean.getNvc_Name());
                if (currentMusic == dataBean.getI_Id()) {
                    //新建Drawable
                    Drawable drawable = getResources().getDrawable(R.mipmap.checked_music);
                    //设置边界，否则无法显示
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    //设定DrawableRight
                    tv_music.setCompoundDrawables(null, null, drawable, null);//画在右边
                }
            }
        };
        lvMusic.setAdapter(musicCommonAdapter);
    }

    //网络请求失败
    @Override
    public void onError(ErrorBean errorBean) {
        CUtils.showToast("数据请求失败");
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopMusic();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Tools.dismissWaitDialog();
        stopMusic();
    }

    // listview条目点击事件
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        MusicBean.DataBean bens = (MusicBean.DataBean) lvMusic.getAdapter().getItem(position);//获得点击item的信息
        currentMusic = bens.getI_Id();//把信息设置个全局的当前id
        currentMusicName = bens.getNvc_Name();////把信息设置个全局的当前名称
        String nvc_path = bens.getNvc_Path();//获得音乐路径
        //播放音乐
        playMusic(nvc_path);
        int childCount = lvMusic.getChildCount();//获得listview总共的item数量
        for (int i = 0; i < childCount; i++) {
            //获得item的内容信息
            MusicBean.DataBean bs = (MusicBean.DataBean) lvMusic.getAdapter().getItem(i);
            //获得item的控件
            LinearLayout item_ll = (LinearLayout) lvMusic.getChildAt(i);
            TextView tv_music = (TextView) item_ll.getChildAt(0);
            if (bs.getI_Id() == currentMusic) {//判断信息
                //新建Drawable
                Drawable drawable = getResources().getDrawable(R.mipmap.checked_music);
                //设置边界，否则无法显示
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                //设定DrawableRight
                tv_music.setCompoundDrawables(null, null, drawable, null);//画在右边
            } else {
                tv_music.setCompoundDrawables(null, null, null, null);//不设置
            }
        }
        musicCommonAdapter.notifyDataSetChanged();//刷新界面
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK) {
            if (oldID != currentMusic) {
                Tools.showSimpleDialog(ThemeMusicActivity.this, "是否保存当前选择的音乐", "取消", "保存", new Tools.ClickListenerInterface() {
                    @Override
                    public void doConfirm() {
                        stopMusic();
                        requsetNetSet();
                    }

                    @Override
                    public void doCancel() {
                        stopMusic();
                        finish();
                    }
                });
                return true;//当更改选项后id不一致拦截返回事件
            } else {
                stopMusic();
                finish();
            }

        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * xutils上传文件
     */
    public void xUpLoading(String url, File file) {
        Log.i("111", "xUpLoading: 上传路径" + url + "上传文件" + file.getPath());
        // 弹框
        Tools.showWaitDialog(this, "上传中...", false);
        HttpManager xhttp = x.http();
        RequestParams requestParams = new RequestParams(url);
        requestParams.addBodyParameter("img", file);
        final long ll = System.currentTimeMillis();
        xhttp.post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Tools.dismissWaitDialog();
                LogUtil.i("httpUtils", "postResult:" + result);
                File defaultFile = FileUtil.getDefaultFile("66.txt");
                try {
                    FileOutputStream fileOutputStream = new FileOutputStream(defaultFile);
                    fileOutputStream.write(result.getBytes());
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                LogUtil.i("httpUtils", "fileOutputStream:" + defaultFile.getPath());
                long lll = System.currentTimeMillis();
                LogUtil.i("jiehuntong", (lll - ll) + "aaaa");
                Message msg = handler.obtainMessage(0);
                msg.obj = result;
                handler.sendMessage(msg);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Tools.dismissWaitDialog();
                LogUtil.i("httpUtils", "postError:" + ex.toString());
                CUtils.showToast("上传失败 ");
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    String result = msg.obj.toString();
                    if (!TextUtils.isEmpty(result)) {
                        Gson gson = new Gson();
                        UpMusicBean newMusic = gson.fromJson(result, new TypeToken<UpMusicBean>() {
                        }.getType());
                        Log.i("4545", "111");
                        if (newMusic != null && newMusic.getResCode().equals("0000")) {
                            if (newMusic != null && newMusic.getResCode().equals("0000")) {
                                currentMusic = newMusic.getData().getI_Id();
                                currentMusicName = newMusic.getData().getNvc_Name();
                                playMusic(newMusic.getData().getNvc_Path());
                                getNetMusics();
                            }
                        } else {
                            CUtils.showToast(newMusic.getMsg());
                        }
                        // 取消弹框
                        Tools.dismissWaitDialog();


                    } else {
                        CUtils.showToast("上传失败");
                    }
                    break;
            }
        }
    };

    private void uploadfiles(File saveFile) {
        // 视频上传地址
        final String url = RequestCode.SURL + RequestCode.UPLOADMUSIC + uId + "&musicName=" + saveFile.getName();
        // 弹框
        Tools.showWaitDialog(this, "上传中...", false);
        HttpManager xhttp = x.http();
        RequestParams requestParams = new RequestParams(url);
        requestParams.addBodyParameter("img", saveFile);
        final long ll = System.currentTimeMillis();
        xhttp.post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Tools.dismissWaitDialog();
                LogUtil.i("httpUtils", "postResult:" + result);
                long lll = System.currentTimeMillis();
                LogUtil.i("jiehuntong", (lll - ll) + "aaaa");
                Message msg = handler.obtainMessage(0);
                msg.obj = result;
                handler.sendMessage(msg);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Tools.dismissWaitDialog();
                LogUtil.i("httpUtils", "postError:" + ex.toString());
                CUtils.showToast("上传失败 ");
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }
}
